package com.example.spider.task;

import com.example.spider.event.listener.SpiderUrlsManager;
import com.example.spider.spider.Spider;
import com.example.spider.starter.SpiderStarter;
import com.example.spider.util.NetWorkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.util.unit.DataSize;

import java.util.List;

/**
 * 爬虫结果处理器
 *
 * @author lym
 */
@SuppressWarnings("rawtypes")
@Slf4j
public class VirtualThreadSpiderManager extends SpiderManager {

    private final DataSize dataSize;

    public VirtualThreadSpiderManager(Spider spider, SpiderResultHandlerManager resultHandlerManager,
                                      SpiderUrlsManager spiderUrlsManager, @Nullable List<SpiderStarter> spiderStarters,
                                      DataSize dataSize) {

        super(spider, resultHandlerManager, spiderUrlsManager, spiderStarters, null);
        this.dataSize = dataSize;
    }

    public boolean canAccept() {
        return NetWorkUtil.getCurrentSpeed().down() < dataSize.toBytes();
    }

    protected <T> void commitSpiderTask(AbstractSpiderTask<T> task) {
        Thread.ofVirtual().name("spider").start(() -> {
            T result = spider.doSpider(task);
            resultHandlerManager.handle(task, result);
        });
    }

}
